Imports System.IO
Imports System.Windows.Forms
Imports DemosCommonCode.Pdf.Security
Imports Vintasoft.Pdf
Imports Vintasoft.Pdf.Security

Namespace Pdf
	Public Class PdfDemosTools

		#Region "Properties"

		Shared _useCustomFontProgramsController As Boolean = False
		''' <summary>
		''' Sets the <see cref="CustomFontProgramsController"/> for
		''' all opened documents (uses <see cref="PdfDocumentController.DocumentOpened"/> event).
		''' </summary>
		Public Shared Property UseCustomFontProgramsController() As Boolean
			Get
				Return _useCustomFontProgramsController
			End Get
			Set
				If _useCustomFontProgramsController <> value Then
					_useCustomFontProgramsController = value
					If value Then
						AddHandler PdfDocumentController.DocumentOpened, New EventHandler(Of PdfDocumentOpenedEventArgs)(AddressOf ConnectCustomFontProgramsController)
					Else
						RemoveHandler PdfDocumentController.DocumentOpened, AddressOf ConnectCustomFontProgramsController
					End If
				End If
			End Set
		End Property

		Shared _enableAuthenticateRequest As Boolean = False
		Public Shared Property EnableAuthenticateRequest() As Boolean
			Get
				Return _enableAuthenticateRequest
			End Get
			Set
				If _enableAuthenticateRequest <> value Then
					_enableAuthenticateRequest = value
					If value Then
						AddHandler PdfDocumentController.AuthenticateRequest, New EventHandler(Of PdfDocumentOpenedEventArgs)(AddressOf PdfDocumentController_AuthenticateRequest)
					Else
						RemoveHandler PdfDocumentController.AuthenticateRequest, AddressOf PdfDocumentController_AuthenticateRequest
					End If
				End If
			End Set
		End Property

		#End Region



		#Region "Methods"

		Private Shared Sub ConnectCustomFontProgramsController(sender As Object, e As Vintasoft.Pdf.PdfDocumentOpenedEventArgs)
			e.Document.FontProgramsController = New CustomFontProgramsController(e.Document)
		End Sub

		Private Shared Sub PdfDocumentController_AuthenticateRequest(sender As Object, e As Vintasoft.Pdf.PdfDocumentOpenedEventArgs)
			Dim document As PdfDocument = e.Document
			While True
				Dim enterPasswordDialog As New PasswordForm()
				If e.Document.SourceStream IsNot Nothing AndAlso TypeOf e.Document.SourceStream Is FileStream Then
					enterPasswordDialog.Filename = DirectCast(e.Document.SourceStream, FileStream).Name
				End If
				If enterPasswordDialog.ShowDialog() = DialogResult.OK Then
					If document.Authenticate(enterPasswordDialog.Password) = AuthorizationResult.IncorrectPassword Then
						MessageBox.Show("The password is incorrect.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
					Else
						Exit While
					End If
				Else
					Return
				End If
			End While
		End Sub

		#End Region

	End Class
End Namespace
